package com.czmh.etc.onlinepubsys.messagehandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.czmh.etc.onlinepubsys.maper.EtcUserMapper;
import com.czmh.etc.onlinepubsys.model.EtcUser;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Slf4j
@Component
public class UnsubscribeEventMessageHander implements WxMpMessageHandler {
    @Autowired
    private EtcUserMapper     etcUserMapper;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage message, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		log.info("用户取消了关注==========");
		//发送者帐号
		String fromUser=message.getFromUser();
		String lang = "zh_CN"; //语言
		WxMpUser wpMpUser = wxMpService.getUserService().userInfo(fromUser,lang);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("openid", wpMpUser.getOpenId());
        List<EtcUser> all = etcUserMapper.getAll(params);
        if (!all.isEmpty()) {
            EtcUser etcUser = all.get(0);
            EtcUser update = new EtcUser(etcUser.getUser_id());
            update.setSubscribe(0);
            etcUserMapper.update(update);
            log.info(String.format("[更新用户状态为取消关注] 用户id：\"%s\"", etcUser.getUser_id()));
        } else {
            log.info(String.format("[用户不存在] openid：\"%s\"", wpMpUser.getOpenId()));
        }
		return null;
	}
}